﻿#include "videocallthread.h"
#include <QHostAddress>

VideoCallThread::VideoCallThread(QWidget *parent,QString id)
{
    this->id = id;
    sock =  new QTcpSocket(this);
    sock->connectToHost(QHostAddress("192.168.43.91"),10089);//连接服务器
    connect(sock,&QTcpSocket::connected,[=](){
        sock->write(id.toUtf8(),id.toUtf8().length()+1);
        sleep(500);
        camera = new QCamera(this);
        viewfinder = new QCameraViewfinder(parent);
        imgcaptrue = new QCameraImageCapture(camera);
        camera->setViewfinder(viewfinder);
        camera->setCaptureMode(QCamera::CaptureStillImage);
        camera->start();
        timer = new QTimer(this);
        connect(timer,&QTimer::timeout,[=](){
            imgcaptrue->capture();
        });
        connect(imgcaptrue, &QCameraImageCapture::imageCaptured, this, &VideoCallThread::displayImage);

        connect(sock,&QTcpSocket::readyRead,[=](){
            QByteArray ba = sock->readAll();
            emit sendImg2(ba);
        });

    });


}

QByteArray VideoCallThread::ImageToData(const QImage &image)
{
    QByteArray imageData;
    QBuffer buffer(&imageData);
    image.save(&buffer, "jpg");
    imageData = imageData.toBase64();
    return imageData;
}

QImage VideoCallThread::DataToImage(const QString &data)
{
    QByteArray imageData = QByteArray::fromBase64(data.toLatin1());
    QImage image;
    image.loadFromData(imageData);
    return image;
}

void VideoCallThread::run()
{
    timer->start(100);
    exec();
}

void VideoCallThread::displayImage(int, QImage img)
{
    QByteArray ba = ImageToData(img);
    sock->write(ba);
    emit sendImg(img);
}
